<template>
  <div v-loading="!tableData.length" class="service-wrap">
    <el-row class="row">
      <el-button type="primary" @click="handleAddDialog">+添加客服</el-button>
    </el-row>
    <el-table
      v-if="tableData.length"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        prop="index"
        label="序号"
        width="50"/>
      <el-table-column
        prop="name"
        label="昵称"
        width="200"/>
      <el-table-column
        prop="phone"
        label="电话"
        width="180"/>
      <el-table-column
        prop="wechat"
        label="微信号"
        width="220"/>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleDialogClick(scope)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>10 && tableData.length" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogFormVisible" :title="title">
      <el-form ref="service" :model="form" :rules="formRules" auto-complete="on">
        <el-form-item :label-width="formLabelWidth" label="昵称" prop="name">
          <el-input v-model="form.name" name="name" type="text" auto-complete="on" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="电话号码" prop="phone">
          <el-input v-model="form.phone" name="phone" type="text" auto-complete="on" placeholder="请输入电话号码"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="微信号码" prop="wechat">
          <el-input v-model="form.wechat" name="wechat" type="text" auto-complete="on" placeholder="请输入微信号"/>
        </el-form-item>
        <!-- <el-form-item :label-width="formLabelWidth" label="排序" prop="wechat">
          <el-input v-model="form.codesort" name="wechat" type="text" auto-complete="on" placeholder="排序号"/>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddService">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { isvalidUsername, validatePhone } from '@/utils/validate'
import Pagination from '@/components/Pagination'
import { addDictionary, findChild, update } from '@/api/data'
export default {
  name: 'BasicService',
  components: {
    Pagination
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validatePhone(value)) {
        callback(new Error('请输入正确的电话号码'))
      } else {
        callback()
      }
    }
    const validateWechat = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入正确的微信号码'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      title: '添加客服',
      formLabelWidth: '100px',
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateUsername }],
        phone: [{ required: true, trigger: 'blur', validator: validateMobile }],
        wechat: [{ required: true, trigger: 'blur', validator: validateWechat }]
      },
      form: {
        name: '',
        phone: '',
        wechat: '',
        codesort: 0
      },
      tableData: [],
      dialogFormFlag: 0,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },
      nameLen: 0,
      phoneLen: 0,
      wechatLen: 0,
      nameId: '1955b0cd29724c9abaa375e7d4d87edf',
      phoneId: '6deeab1afb2f4352a7bdcc3ccd776f6c',
      wechatId: 'c907dfb3c2d34f97857803544e94c3fc',
      nameArray: [],
      phoneArray: [],
      wechatArray: [],
      scope: {}
    }
  },
  watch: {
    nameArray(arr) {
      const propName = item => {
        return {
          name: item.name,
          nameId: item.id
        }
      }
      this.changeTable(arr, propName)
    },
    phoneArray(arr) {
      const propName = item => {
        return {
          phone: item.name,
          phoneId: item.id
        }
      }
      this.changeTable(arr, propName)
    },
    wechatArray(arr) {
      const propName = item => {
        return {
          wechat: item.name,
          wechatId: item.id
        }
      }
      this.changeTable(arr, propName)
    }
  },
  created() {
    const pagesize = (this.listQuery.page - 1) * this.listQuery.limit
    this.getInfo(pagesize)
  },
  methods: {
    getInfo(iDisplayStart) {
      Promise.all([findChild(this.nameId, iDisplayStart), findChild(this.phoneId, iDisplayStart), findChild(this.wechatId, iDisplayStart)])
        .then((res) => {
          res.map((item, index) => {
            if (index === 0) {
              this.nameLen = item.total
              this.total = item.total
              this.nameArray = item.data.reverse()
            }
            if (index === 1) {
              this.phoneLen = item.total
              this.phoneArray = item.data.reverse()
            }
            if (index === 2) {
              this.wechatLen = item.total
              this.wechatArray = item.data.reverse()
            }
          })
        }).catch((res) => {
          this.$message.warning({
            duration: 1000,
            message: '请稍后再试'
          })
        })
    },
    handleAddService() {
      this.$refs['service'].validate((valid, object) => {
        if (valid) {
          this.title === '添加客服' ? this.addService() : this.modification()
          // this.dialogFormVisible = false
        }
      })
    },
    handleDialogClick(scope) {
      const { name, phone, wechat, codesort } = scope.row
      this.title = '修改资料'
      this.dialogFormVisible = true
      this.dialogFormFlag = 1
      this.scope = scope
      this.form = {
        name,
        phone,
        wechat,
        codesort
      }
    },
    handleAddDialog() {
      this.title = '添加客服'
      this.dialogFormVisible = true
      this.dialogFormFlag = 0
    },
    getList(prop) {
      this.tableData = []
      this.listQuery.page = prop.page
      this.listQuery.limit = prop.limit
      const pagesize = (prop.page - 1) * prop.limit
      this.getInfo(pagesize)
    },
    addService() {
      const pagesize = (this.listQuery.page - 1) * this.listQuery.limit
      this.tableData = []
      Promise.all([addDictionary(this.nameId, `name-${this.nameLen + 1}`, this.form.name, this.nameLen), addDictionary(this.phoneId, `phone-${this.phoneLen + 1}`, this.form.phone, this.phoneLen), addDictionary(this.wechatId, `wechat-${this.wechatLen + 1}`, this.form.wechat, this.wechatLen)])
        .then((res) => {
          const flag = res.every((item) => {
            return item.success
          })
          if (flag) {
            this.$message.success({
              duration: 1000,
              message: '添加成功'
            })
            this.getInfo(pagesize)
          }
        }).catch((res) => {
          this.$message.error({
            duration: 1000,
            message: '添加失败'
          })
        })
    },
    modification() {
      const pagesize = (this.listQuery.page - 1) * this.listQuery.limit
      this.tableData = []
      const scope = this.scope
      Promise.all([update(scope.row.nameId, this.form.name, scope.row.codesort), update(scope.row.phoneId, this.form.phone, scope.row.codesort), update(scope.row.wechatId, this.form.wechat, scope.row.codesort)])
        .then((res) => {
          const flag = res.every((item) => {
            return item.success
          })
          if (flag) {
            this.$message.success({
              duration: 1000,
              message: '修改成功'
            })
            this.getInfo(pagesize)
          }
        }).catch((res) => {
          this.$message.error({
            duration: 1000,
            message: '修改失败'
          })
        })
    },
    changeTable(arr, prop) {
      const pageSize = (this.listQuery.page - 1) * this.listQuery.limit + 1
      const tableData = this.tableData
      if (!Array.isArray(arr)) return
      arr.map((item, index) => {
        const i = Number(item.code.split('-')[1]) - pageSize
        tableData[i] = Object.assign({}, { ...tableData[i] }, { index: i + 1, codesort: item.codesort }, { ...prop(item) })
      })
      this.tableData = [...tableData]
    }
  }
}
</script>
<style lang="scss" scoped>
.service-wrap {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  .row {
    margin-bottom: 20px;
  }
}
</style>
